package com.xauto.pioneer.appuser.util;

import android.app.Activity;
import android.content.Context;
import android.util.Log;

import com.xauto.pioneer.appuser.http.BaseLHttpHandler;
import com.xauto.pioneer.appuser.http.Constants;
import com.xauto.pioneer.appuser.http.LHttpLib;
import com.xauto.pioneer.appuser.interfaces.AccountInfoCallBack;
import com.xauto.pioneer.appuser.interfaces.CarOrderInfoCallBack;
import com.xauto.pioneer.appuser.interfaces.CommonCallBack;
import com.xauto.pioneer.appuser.interfaces.ConfigCallBack;
import com.xauto.pioneer.appuser.interfaces.DeviceOrderInfoCallBack;
import com.xauto.pioneer.appuser.interfaces.MemberCallBack;
import com.xauto.pioneer.appuser.interfaces.MemberDepositCallBack;
import com.xauto.pioneer.appuser.interfaces.OrdercostInfoCallBack;
import com.xauto.pioneer.appuser.interfaces.RegionListCallBack;
import com.xauto.pioneer.appuser.interfaces.ShareInfoCallBack;
import com.xauto.pioneer.appuser.interfaces.TokenCallBack;
import com.xauto.pioneer.appuser.interfaces.WebInfoCallBack;
import com.xauto.pioneer.appuser.model.AccountInfo;
import com.xauto.pioneer.appuser.model.Bank;
import com.xauto.pioneer.appuser.model.BillRule;
import com.xauto.pioneer.appuser.model.CarOrderInfo;
import com.xauto.pioneer.appuser.model.CheckoutMemberAccountInfo;
import com.xauto.pioneer.appuser.model.ClientSetting;
import com.xauto.pioneer.appuser.model.ClientVersion;
import com.xauto.pioneer.appuser.model.ConfigVersion;
import com.xauto.pioneer.appuser.model.DeviceOrderInfo;
import com.xauto.pioneer.appuser.model.JSONStatus;
import com.xauto.pioneer.appuser.model.Member;
import com.xauto.pioneer.appuser.model.MemberDeposit;
import com.xauto.pioneer.appuser.model.OrderCostInfo;
import com.xauto.pioneer.appuser.model.Payment;
import com.xauto.pioneer.appuser.model.Region;
import com.xauto.pioneer.appuser.model.SettingDate;
import com.xauto.pioneer.appuser.model.ShareInfo;
import com.xauto.pioneer.appuser.model.WebInfo;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**公共远程数据加载
 * Created by Ellis.Li on 2017/5/3.
 */

public class DataLoadUtil {
//临时解决方案
    public static String Runkilometre;//运行距离
    public static Double RunTimeValue;//运行时间金额
    public static Double RunkilometreValue;//运行公里金额
    public static String RunValue;//运行公里金额
    public static Double total_credit_amount;//信用金额
    /**
     * 加载基本信息Member
     */
    public static void refreshMemberData(final Context mContext){
        if (!DataCheckUtil.isLogin(mContext))return;
        String memberId = PreferencesUtils.getString(mContext, Constants.KEY_MEMBER_ID);
        new LHttpLib().getMemberDetail(mContext, memberId, new BaseLHttpHandler(mContext,false,false){
            @Override
            public void onSuccess(JSONStatus jsonStatus) {
                super.onSuccess(jsonStatus);
                Member member = new Member().parse(jsonStatus.data.optJSONObject("member_info"));
                PreferencesUtils.putString(mContext, Constants.KEY_MEMBER_OBJECT, SerializeUtil.serialize(member));
            }
        });
    }
    /**
     * 加载基本信息Member(带回调函数)
     */
    public static void refreshMemberData(final Context mContext, final MemberCallBack memberCallBack){
        if (!DataCheckUtil.isLogin(mContext))return;
        String memberId = PreferencesUtils.getString(mContext, Constants.KEY_MEMBER_ID);
        new LHttpLib().getMemberDetail(mContext, memberId, new BaseLHttpHandler(mContext,false,false){
            @Override
            public void onSuccess(JSONStatus jsonStatus) {
                super.onSuccess(jsonStatus);
                Member member = new Member().parse(jsonStatus.data.optJSONObject("member_info"));
                PreferencesUtils.putString(mContext, Constants.KEY_MEMBER_OBJECT, SerializeUtil.serialize(member));
                memberCallBack.getMember(member);
            }
        });
    }
    /**
     * 加载Member消息(带回调函数)
     */
    public static void refreshMemberMessageInfo(final Context mContext, final MemberCallBack memberCallBack){
        if (!DataCheckUtil.isLogin(mContext))return;
        String memberId = PreferencesUtils.getString(mContext, Constants.KEY_MEMBER_ID);
        new LHttpLib().getMemberDetail(mContext, memberId, new BaseLHttpHandler(mContext,false,false){
            @Override
            public void onSuccess(JSONStatus jsonStatus) {
                super.onSuccess(jsonStatus);
                Member member = new Member().parse(jsonStatus.data.optJSONObject("member_info"));
                PreferencesUtils.putString(mContext, Constants.KEY_MEMBER_OBJECT, SerializeUtil.serialize(member));
                memberCallBack.getMember(member);
            }
        });
    }
    /**
     * 获取地区列表
     */
    public static void getRegionList(final Context mContext, final RegionListCallBack regionListCallBack){
//        if (!DataCheckUtil.isLogin(mContext))return;
        new LHttpLib().getRegionList(mContext, new BaseLHttpHandler(mContext,false,false){
            @Override
            public void onSuccess(JSONStatus jsonStatus) {
                super.onSuccess(jsonStatus);
                List<Region> regionList = null;
                JSONArray regionArray = jsonStatus.data.optJSONArray("region_list");
                if (regionArray != null){
                    regionList = new ArrayList<Region>();
                    int length = regionArray.length();
                    for (int i=0;i<length;i++){
                        Region region = new Region().parse(regionArray.optJSONObject(i));
                        regionList.add(region);
                    }
                     PreferencesUtils.putString(mContext, Constants.KEY_REGION_LIST_OBJECT, SerializeUtil.serialize(regionList));
                     regionListCallBack.getRegionList(regionList);
                }
            }
        });
    }
    /**
     * 获取配置信息
     */
    public static void getConfig(final Context mContext, final ConfigCallBack callBack){
//        if (!DataCheckUtil.isLogin(mContext))return;
        new LHttpLib().getConfig(mContext, new BaseLHttpHandler(mContext,false,false){
            @Override
            public void onSuccess(JSONStatus jsonStatus) {
                super.onSuccess(jsonStatus);
                JSONArray dataArray = jsonStatus.data.optJSONArray("config_list");
                if (dataArray != null){
                    int length = dataArray.length();
                    ConfigVersion configVersion = new ConfigVersion();
                    for (int i=0;i<length;i++){
                        JSONObject itemData = dataArray.optJSONObject(i);
                        String key = itemData.optString("key");
                        String value = itemData.optString("value");
                        JSONArray data = null;
                        JSONObject dataObject = null;
                        PreferencesUtils.putString(mContext,key,value);
                        switch (key){
                            case "region":
                                data = itemData.optJSONArray("data");
                                configVersion.setRegion(value);
                                if (data != null){
                                    for (int j=0,dataLength = data.length();j<dataLength;j++){
                                        Region region = new Region().parse(data.optJSONObject(j));
                                        region.saveDb(mContext,region);
                                    }
                                }
                                break;
                            case "bank":
                                data = itemData.optJSONArray("data");
                                configVersion.setBank(value);
                                if (data != null){
                                    for (int j=0,dataLength = data.length();j<dataLength;j++){
                                        Bank bank = new Bank().parse(data.optJSONObject(j));
                                        bank.saveDb(mContext,bank);
                                    }
                                }
                                break;
                            case "payment":
                                data = itemData.optJSONArray("data");
                                configVersion.setPayment(value);
                                if (data != null){
                                    for (int j=0,dataLength = data.length();j<dataLength;j++){
                                        Payment payment = new Payment().parse(data.optJSONObject(j));
                                        payment.saveDb(mContext,payment);
                                    }
                                }
                                break;
                            case "billing_rules":
                                data = itemData.optJSONArray("data");
                                configVersion.setBilling_rules(value);
                                if (data != null){
                                    for (int j=0,dataLength = data.length();j<dataLength;j++){
                                        BillRule billRule = new BillRule().parse(data.optJSONObject(j));
                                        billRule.saveDb(mContext,billRule);
                                    }
                                }
                                break;
                            case "setting_date":
                                break;
                            case "client_version":
                                dataObject = itemData.optJSONObject("data");
                                if (dataObject != null){
                                    ClientVersion clientVersion = new ClientVersion().parse(dataObject);
                                    clientVersion.saveDb(mContext,clientVersion);
                                }
                                break;
                            case "client_setting":
                                dataObject = itemData.optJSONObject("data");
                                if (dataObject != null){
                                    ClientSetting clientSetting = new ClientSetting().parse(dataObject);
                                    clientSetting.saveDb(mContext,clientSetting);
                                }
                                break;
                        }
                    }
                    configVersion.saveDb(mContext,configVersion);
                }
                callBack.getConfig();
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                callBack.getConfig();
            }
        });
    }
    /**
     * 开启车辆订单
     */
    public static void startCarOrder(final Context mContext,String carNo,final CarOrderInfoCallBack carOrderInfoCallBack){
        if (!DataCheckUtil.isLogin(mContext))return;
        String memberId = PreferencesUtils.getString(mContext, Constants.KEY_MEMBER_ID);
        new LHttpLib().startCarOrder(mContext, memberId, carNo,new BaseLHttpHandler(mContext,true,true){
            @Override
            public void onSuccess(JSONStatus jsonStatus) {
                super.onSuccess(jsonStatus);
                CarOrderInfo carOrderInfo = new CarOrderInfo().parse(jsonStatus.data.optJSONObject("car_order_info"));
                carOrderInfoCallBack.getCarOrderInfo(carOrderInfo);
            }
        });
    }
    /**
     * 获取车辆订单详情
     */
    public static void getCarOrderDetail(final Context mContext,String car_order_no,final CarOrderInfoCallBack carOrderInfoCallBack){
//getCarOrderDetail
        if (!DataCheckUtil.isLogin(mContext))return;
        String memberId = PreferencesUtils.getString(mContext, Constants.KEY_MEMBER_ID);
        new LHttpLib().getCarOrderDetailInfo(mContext, memberId, car_order_no,new BaseLHttpHandler(mContext,true,true){
            @Override
            public void onSuccess(JSONStatus jsonStatus) {
                super.onSuccess(jsonStatus);
                CarOrderInfo carOrderInfo = new CarOrderInfo().parse(jsonStatus.data.optJSONObject("car_order_info"));



                carOrderInfoCallBack.getCarOrderInfo(carOrderInfo);
            }
        });
    }
    /**
     * 获取车辆订单详情订单运行中
     */
    public static void getCarOrderDetailOrderRun(boolean stats,final Context mContext,String car_order_no,final CarOrderInfoCallBack carOrderInfoCallBack){
//getCarOrderDetail
        if (!DataCheckUtil.isLogin(mContext))return;
        String memberId = PreferencesUtils.getString(mContext, Constants.KEY_MEMBER_ID);
        new LHttpLib().getCarOrderDetail(mContext, memberId, car_order_no,new BaseLHttpHandler(mContext,stats,true){
            @Override
            public void onSuccess(JSONStatus jsonStatus) {
                super.onSuccess(jsonStatus);
                CarOrderInfo carOrderInfo = new CarOrderInfo().parse(jsonStatus.data.optJSONObject("car_order_info"));
                carOrderInfoCallBack.getCarOrderInfo(carOrderInfo);
            }
        });
    }
    /**
     * 获取车辆结算详情
     * */
    public static void getOrdercostRun(boolean stats,final Context mContext,String car_order_no,
                                       String payment_code, String voucher_member_id,
                                       String is_use_balance_amount,final OrdercostInfoCallBack ordercostInfoCallBack){
        if (!DataCheckUtil.isLogin(mContext))return;
        String memberId = PreferencesUtils.getString(mContext, Constants.KEY_MEMBER_ID);
        new LHttpLib().checkoutOrder(mContext,memberId,car_order_no,payment_code,voucher_member_id,
                is_use_balance_amount,new BaseLHttpHandler(mContext,stats,true){
            @Override
            public void onSuccess(JSONStatus jsonStatus) {
                super.onSuccess(jsonStatus);
                OrderCostInfo orderCostInfo = new OrderCostInfo().parse(jsonStatus.data.optJSONObject("car_order_info"));
                CheckoutMemberAccountInfo memberAccountInfo =
                        new CheckoutMemberAccountInfo().parse(jsonStatus.data.optJSONObject("member_account_info"));
                Log.e("tag","accountInfo = "+memberAccountInfo.toString());
                ordercostInfoCallBack.getOrdercostInfo(orderCostInfo,memberAccountInfo);
            }
        });
    }
    /**
     * 获取会员账户信息
     */
    public static void getMemberAccountInfo(final Context mContext,final AccountInfoCallBack accountInfoCallBack){
        String memberId = PreferencesUtils.getString(mContext, Constants.KEY_MEMBER_ID);
        new LHttpLib().getMemberAccountInfo(mContext, memberId, new BaseLHttpHandler(mContext,false,false){
            @Override
            public void onSuccess(final JSONStatus jsonStatus) {
                super.onSuccess(jsonStatus);
                ((Activity)mContext).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        AccountInfo accountInfo = new AccountInfo().parse(jsonStatus.data.optJSONObject("member_account_info"));
                        accountInfoCallBack.getAccountInfo(accountInfo);
                        PreferencesUtils.putString(mContext, Constants.KEY_MEMBER_ACCOUNT_OBJECT, SerializeUtil.serialize(accountInfo));

                    }
                });
            }
        });
    }
    /**
     * 获取分享相关信息
     */
    public static void getShareInfo(final Context mContext,final String share_type,final ShareInfoCallBack shareInfoCallBack){
        new LHttpLib().getShareInfo(mContext, share_type, new BaseLHttpHandler(mContext,true,true){
            @Override
            public void onSuccess(final JSONStatus jsonStatus) {
                super.onSuccess(jsonStatus);
                ((Activity)mContext).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ShareInfo shareInfo = new ShareInfo().parse(jsonStatus.data.optJSONObject("share_info"));
                        shareInfoCallBack.getShareInfo(shareInfo);
                    }
                });
            }
        });
    }

    /**
     * 13接口
     * @param mContext
     * @param requestType
     * @param car_order_no
     * @param car_no
     * @param webInfoCallBack
     */
    public static void getWebInfo(final Context mContext,final String requestType,String car_order_no,String car_no, final WebInfoCallBack webInfoCallBack) {
        String memberId = PreferencesUtils.getString(mContext, Constants.KEY_MEMBER_ID);
        new LHttpLib().getWebInfo(mContext, requestType, memberId,car_order_no,car_no,new BaseLHttpHandler(mContext, true, true) {
            @Override
            public void onSuccess(JSONStatus jsonStatus) {
                super.onSuccess(jsonStatus);
                final WebInfo webInfo = new WebInfo().parse(jsonStatus.data);
                if (webInfo != null)webInfoCallBack.getWebInfo(webInfo);

            }
        });
    }
    /**
     * 30接口 获取车辆计费规则
     * @param mContext
     */
    public static void getCarBillingRulesList(final Context mContext, final CommonCallBack commonCallBack) {
        new LHttpLib().getCarBillingRulesList(mContext,new BaseLHttpHandler(mContext, false, false) {
            @Override
            public void onSuccess(JSONStatus jsonStatus) {
                super.onSuccess(jsonStatus);
                JSONArray dataArray = jsonStatus.data.optJSONArray("billing_rules_list");
                if (dataArray != null){
                    int length = dataArray.length();
                    for (int i=0;i<length;i++) {
                        BillRule billRule = new BillRule().parse(dataArray.optJSONObject(i));
                        billRule.saveDb(mContext,billRule);
                    }
                }
                commonCallBack.getCallBack();
            }
        });
    }
    /**
     * 04接口 获取银行列表
     * @param mContext
     */
    public static void getBankList(final Context mContext,String userType ,final CommonCallBack commonCallBack) {
        new LHttpLib().getBankList(mContext,userType,new BaseLHttpHandler(mContext, false, false) {
            @Override
            public void onSuccess(JSONStatus jsonStatus) {
                super.onSuccess(jsonStatus);
                JSONArray dataArray = jsonStatus.data.optJSONArray("bank_list");
                if (dataArray != null){
                    int length = dataArray.length();
                    for (int i=0;i<length;i++) {
                        Bank bank = new Bank().parse(dataArray.optJSONObject(i));
                        bank.saveDb(mContext,bank);
                    }
                }
                commonCallBack.getCallBack();
            }
        });
    }
    /**
     * 31接口 获取日期数据列表
     * @param mContext
     */
    public static void getSettingDateList(final Context mContext,String start_date,String end_date, final CommonCallBack commonCallBack) {
        new LHttpLib().getSettingDateList(mContext,start_date,end_date,new BaseLHttpHandler(mContext, false, false) {
            @Override
            public void onSuccess(JSONStatus jsonStatus) {
                super.onSuccess(jsonStatus);
                JSONArray dataArray = jsonStatus.data.optJSONArray("setting_date_list");
                if (dataArray != null){
                    int length = dataArray.length();
                    for (int i=0;i<length;i++) {
                        SettingDate settingDate = new SettingDate().parse(dataArray.optJSONObject(i));
                        settingDate.saveDb(mContext,settingDate);
                    }
                }
                commonCallBack.getCallBack();
            }
        });
    }
    /**
     * 提交推送设备信息
     */
    public static void editPushDevice(final Context mContext,String mobile_token,final CommonCallBack commonCallBack){
        if (!DataCheckUtil.isLogin(mContext))return;
        String memberId = PreferencesUtils.getString(mContext, Constants.KEY_MEMBER_ID);
        new LHttpLib().editPushDevice(mContext, memberId, mobile_token,new BaseLHttpHandler(mContext,false,false){
            @Override
            public void onSuccess(JSONStatus jsonStatus) {
                super.onSuccess(jsonStatus);
                commonCallBack.getCallBack();
            }
        });
    }
    /**
     * 更新token
     */
    public static void loginWithToken(final Context mContext,final TokenCallBack tokenCallBack){
        if (!DataCheckUtil.isLogin(mContext))return;
        String memberId = PreferencesUtils.getString(mContext, Constants.KEY_MEMBER_ID);
        new LHttpLib().loginWithToken(mContext, memberId,new BaseLHttpHandler(mContext,false,true){
            @Override
            public void onSuccess(JSONStatus jsonStatus) {
                super.onSuccess(jsonStatus);
                //更新token信息
                String member_id = jsonStatus.data.optString("member_id");
                String token = jsonStatus.data.optString("token");
                PreferencesUtils.putString(mContext, Constants.KEY_MEMBER_ID, member_id);
                PreferencesUtils.putString(mContext, Constants.KEY_TOKEN, token);
                tokenCallBack.getToken(token);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }
    /**
     * 获取保证金详情
     */
    public static void getDepositDetail(final Context mContext,boolean isShowLoading,final MemberDepositCallBack memberDepositCallBack){
        String memberId = PreferencesUtils.getString(mContext, Constants.KEY_MEMBER_ID);
        new LHttpLib().getDepositDetail(mContext, memberId,new BaseLHttpHandler(mContext,isShowLoading,isShowLoading){
            @Override
            public void onSuccess(JSONStatus jsonStatus) {
                super.onSuccess(jsonStatus);
                //更新token信息
                MemberDeposit memberDeposit = new MemberDeposit().parse(jsonStatus.data.optJSONObject("member_deposit_info"));
                memberDepositCallBack.getMemberDeposit(memberDeposit);
            }
        });
    }
    /**
     * 获取当前账号订单详情
     */
    public static void getDeviceNotifyInfo(final Context mContext,boolean isShowLoading,final DeviceOrderInfoCallBack deviceOrderInfoCallBack){
        if (!DataCheckUtil.isLogin(mContext))return;
        String memberId = PreferencesUtils.getString(mContext, Constants.KEY_MEMBER_ID);
        new LHttpLib().getDeviceNotifyInfo(mContext, memberId,new BaseLHttpHandler(mContext,isShowLoading,isShowLoading){
            @Override
            public void onSuccess(JSONStatus jsonStatus) {
                super.onSuccess(jsonStatus);
                DeviceOrderInfo deviceOrderInfo = new DeviceOrderInfo().parse(jsonStatus.data.optJSONObject("device_notify_info"));
                if (deviceOrderInfo != null)deviceOrderInfoCallBack.getCallBack(deviceOrderInfo);
            }
        });
    }
}
